package com.zxy.demo.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zxy.demo.common.ModelResult;

/**
 * 自定义的异常处理Controller
 * @author ZENG.XIAO.YAN
 * @blog  http://www.cnblogs.com/zeng1994/
 * @version 1.0
 */
@Controller
@RequestMapping("/myCustomError")
public class CustomExceptionController  {
	
	// 处理请求页面的请求，返回的是页面
	@RequestMapping(produces = "text/html")
	public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mov = new ModelAndView();
		response.setStatus(500);
		Exception e = (Exception) request.getAttribute("Exception");
		// 状态码，异常信息输出到页面
		mov.addObject("code", 500);
		mov.addObject("model", ExceptionUtils.getFullStackTrace(e));
		mov.addObject("msg", e.getMessage());
		mov.setViewName("myError");
		return mov;
	}
	
	// 不是请求页面时，返回json
	@RequestMapping
	@ResponseBody
	public ModelResult<String> error(HttpServletRequest request) {
		Exception e = (Exception) request.getAttribute("Exception");
		return new ModelResult<String>(500, e.getMessage(), false, ExceptionUtils.getFullStackTrace(e));
	}
	
}
